'use strict';
const uuid = require('uuid/v1')
const fs = require('fs');
const path = require('path');
const toArray = require('stream-to-array');
/*
* @ctx          context对象            必传
* @size         限制文件大小            默认2  单位M
*/
const fileUploadImg = async (ctx, size = 2, folderName) => {
    const stream = await ctx.getFileStream();
    // 判断文件类型，存入对应的目录
    const imgtype = ['image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
    let url = '/public/static/other/'
    if (imgtype.includes(stream.mimeType)) {
        url = '/public/static/image/'
    }
    const catalog = path.join(ctx.app.baseDir, 'app', url)

    // 截取文件类型
    let filename = stream.filename;
    let t = filename.split('.');
    let len = t.length;
    let filetypeName = '.' + t[len - 1];

    // 获取文件大小
    const filesize = parseInt((stream.readableLength / 1024) / 1024);
    if (filesize > size) {
        ctx.throw(403, '文件大大了兄弟，最多' + size + 'M');
    }

    try {
        const parts = await toArray(stream);
        const buf = Buffer.concat(parts);
        const nameid = uuid()
        const target = catalog + nameid + filetypeName;
        fs.writeFileSync(target, buf);
        return url + nameid + filetypeName;
    } catch (e) {
        return {
            message: '文件上传失败'
        }
    }
}

const Controller = require('../base.js');

class FileController extends Controller {
    // 上传头像图片
    async head() {
        const { ctx } = this;
        try {
            let url = await fileUploadImg(ctx);
            ctx.success({
                url
            })
        } catch (e) {
            ctx.throw(403, e.message)
        }

    }
}

module.exports = FileController;